<?php
declare(strict_types=1);

namespace SixShop\Balpay\Entity;

use app\model\User;
use SixShop\Core\Helper;
use SixShop\Balpay\Enum\BalpayLogTypeEnum;
use SixShop\Core\Entity\BaseEntity;
use think\Paginator;

/**
 * @mixin \SixShop\Balpay\Model\ExtensionBalpayLogModel
 */
class ExtensionBalpayLogEntity extends BaseEntity
{

    public function change(int $userID, float $amount, BalpayLogTypeEnum $type, string $description, int $orderID = 0): void
    {
        $user = User::withTrashed()->find($userID);
        if (!$user) {
            throw new \RuntimeException('用户不存在');
        }
        if ($type->negative()) {
            if ($user->balance < $amount) {
                Helper::throw_logic_exception('余额不足', status: 'not_enough_balance');
            }
            $user->dec('balance', $amount);
            $amount = -$amount;
        } else {
            $user->inc('balance', $amount);
        }
        $this->transaction(function () use ($user, $amount, $type, $description, $orderID) {
            $user->save();
            $this->create([
                'user_id' => $user->id,
                'order_id' => $orderID,
                'amount' => $amount,
                'type' => $type,
                'description' => $description,
                'balance' => $user->balance,
            ]);
        });
    }

    public function getList(int $user_id, ?BalpayLogTypeEnum $type, array $pageAndLimit): Paginator
    {
        return $this->where('user_id', $user_id)
            ->when($type, fn($query) => $query->where('type', $type))
            ->append(['type_text'])
            ->order('id', 'desc')
            ->paginate($pageAndLimit);
    }
}